package com.ifish.leetcode.problem.algorithm;

import com.ifish.leetcode.problem.BaseLeetCodeProblem;

/**
 * Created by iFish on 2017/7/9.
 */

public class _0004 extends BaseLeetCodeProblem {

    @Override
    public String title() {
        return "Median of Two Sorted Arrays";
    }

    @Override
    public int difficulty() {
        return 2;
    }

    @Override
    public void run() {
        super.run();

        int []nums1 = new int[]{1,2};
        int []nums2 = new int[]{3,4};
        double median = findMedianSortedArrays(nums1, nums2);
        printResult(median + "");
    }

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int []numnew = new int[nums1.length + nums2.length];
        int i1 = 0, i2 = 0;
        for (int i = 0; i < numnew.length; i++) {
            int n1 = i1 < nums1.length ? nums1[i1] : Integer.MAX_VALUE;
            int n2 = i2 < nums2.length ? nums2[i2] : Integer.MAX_VALUE;
            if (n1 <= n2) {
                numnew[i] = n1;
                i1++;
            } else {
                numnew[i] = n2;
                i2++;
            }
        }
        if (numnew.length % 2 == 1) {
            return numnew[numnew.length / 2];
        } else {
            return (numnew[numnew.length / 2 - 1] + numnew[numnew.length / 2]) / 2.0;
        }
    }
}
